<?php

namespace app\common\model;

use fast\Tree;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Cache;

/**
 * 地区数据模型.
 */
class Area extends BaseModel
{
    // 表名
    protected $name = 'area';

    /**
     * 检查地址是否提供服务
     * @param string $city 城市名
     * @param string $address 地址
     * @param bool|array $coor 坐标数组[lon,lat]
     * @return bool|string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function checkCity($city,$address,$coor=[]){
        $city_info=[];
        if($address){
            $url="https://restapi.amap.com/v3/geocode/geo?key=b8e09303522f19980c18130a09bc92bf&address={$address}";
            $result=file_get_contents($url);
            if($result){
                $result=json_decode($result,true);
                if($result['status']==1&&isset($result['geocodes'][0])&&$result['geocodes'][0]['city']){
                    $city_info=Area::get(['name'=>$result['geocodes'][0]['city']]);
                }
            }
        }
        elseif($coor&&count($coor)==2){
            $url="https://restapi.amap.com/v3/geocode/regeo?key=b8e09303522f19980c18130a09bc92bf&location={$coor[0]},{$coor[1]}";
            $result=file_get_contents($url);
            if($result){
                $result=json_decode($result,true);
                if($result['status']==1&&isset($result['regeocode'])&&isset($result['regeocode']['addressComponent'])&&$result['regeocode']['addressComponent']['city']){
                    $city_info=Area::get(['name'=>$result['regeocode']['addressComponent']['city']]);
                }
            }
        }

        if($city&&!$city_info){
            $city_info=Area::get(['name'=>$city]);
        }

        if($city_info){
            if($city_info['open']==1){
                return true;
            }
            else{
                return '所选城市服务已暂停' ;
            }
        }
        return '未找到此城市信息';
    }

    /**
     * 获取两地路程
     */
    public static function getDistance($start_lon,$start_lat,$end_lon,$end_lat){
        $url="https://restapi.amap.com/v5/direction/driving?key=b8e09303522f19980c18130a09bc92bf&origin={$start_lon},{$start_lat}&destination={$end_lon},{$end_lat}";
        $result=file_get_contents($url);
        if($result){
            $result=json_decode($result,true);
            if($result['status']==1&&isset($result['route']['paths'][0])&&$result['route']['paths'][0]['distance']){
                return bcdiv($result['route']['paths'][0]['distance'],1000,3);
            }
        }

        return false;
    }


    public function getAreaId($area){
        $arr=explode('/',$area);

        if(count($arr)!=3)
            throw new Exception('请填写完整的所属地信息');

        $province=$this->where(['name'=>$arr[0]])->value('id');
        if(!$province)
            throw new Exception('省份信息错误');

        $city=$this->where(['name'=>$arr[1]])->value('id');
        if(!$city)
            throw new Exception('城市信息错误');

        $county=$this->where(['name'=>$arr[2]])->value('id');
        if(!$county)
            throw new Exception('区县信息错误');


        return [$province,$city,$county];
    }


    public function tree(){
        $ruleList = self::where(['level'=>[1,2]])->order('id', 'asc')->select()->toArray();

        Tree::instance()->init($ruleList);
        $tree = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0),'name',false);

        return $tree;
    }

    public function getTreeList($selected)
    {
        $ruleList = $this->tree();

        $hasChildrens = [];
        foreach ($ruleList as $k => $v) {
            if ($v['haschild']) {
                $hasChildrens[] = $v['id'];
            }
        }
        foreach ($ruleList as $k => $v) {
            $state = ['selected' => in_array($v['id'], $selected) && ! in_array($v['id'], $hasChildrens)];
            $nodeList[] = [
                'id'     => $v['id'],
                'parent' => $v['pid'] ? $v['pid'] : '#',
                'text'   => __($v['name']),
                'type'   => 'menu',
                'state'  => $state,
            ];
        }

        return $nodeList;
    }

    public function getOpenTree(){
        $area_list = self::where(['level'=>[1,2],'open'=>1])->field('id,pid,name,level')->order('level', 'asc')->select()->toArray();

        $list=[];
        foreach($area_list as $al){
            if($al['level']==1)
                $list[$al['id']]=$al;

            if($al['level']==2)
                $list[$al['pid']]['city'][]=$al;
        }

        return array_values($list);
    }
}
